package com.wjwframework.jfinal.web.shiro;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

import com.jfinal.plugin.activerecord.Record;
import com.wjwframework.jfinal.web.constant.Constants;
import com.wjwframework.jfinal.web.model.SysPower;
import com.wjwframework.jfinal.web.model.SysUser;

/**
 * shiro工具类
 */
public class ShiroUtils {
	
	/**
	 * 获取当前登录用户对象
	 * @return
	 */
	public static SysUser getSysUser() {
		Subject subject = SecurityUtils.getSubject();
//		User user=(User) subject.getPrincipal();//直接从登录信息SimpleAuthenticationInfo中获取用户对象
		SysUser sysUser=(SysUser)subject.getSession().getAttribute(Constants.SESSION_USER_KEY);
		return sysUser;
	}
	/**
	 * 获取当前用户主键id
	 * @return
	 */
	public static String getUserId() {
		SysUser sysUser = getSysUser();
		if(sysUser != null) return sysUser.getId();
		return "";
	}
	/**
	 * 获取当前用户名
	 * @return
	 */
	public static String getUserName() {
		SysUser sysUser = getSysUser();
		if(sysUser != null) return sysUser.getUserName();
		throw new RuntimeException("用户名是空的!");
	}
	/**
	 * 获取当前用户角色id
	 * @return
	 */
	public static String getRoleId() {
		SysUser sysUser = getSysUser();
		String role_id = sysUser.getRoleId();
		if(sysUser != null && role_id != null) return role_id;
		return "";
	}
	/**
	 * 获取当前用户角色编码
	 */
	public static String getRoleCoding(){
		SysUser sysUser = getSysUser();
		if(sysUser != null) return sysUser.getStr("coding");
		throw new RuntimeException("角色coding名是空的!");
	}
	/**
	 * 获取当前角色名称
	 */
	public static String getRoleName(){
		SysUser sysUser = getSysUser();
		if(sysUser != null) return sysUser.getStr("role_name");
		throw new RuntimeException("角色名是空的!");
	}
	/**
	 * 获取当前用户权限对象集合
	 * @return
	 */
	public static List<Record> getPowers(){
		Subject subject = SecurityUtils.getSubject();
		List<Record> powerList=(List<Record>)subject.getSession().getAttribute(Constants.SESSION_AUTH_POWER);
		return powerList;
	}
	/**
	 * 获取用户拥有的权限的子权限集合
	 * @return
	 */
	public static List<Record> getPowerListByFatherUrl(String url){
		List<Record> pList=getPowers();
		List<Record> sonPowerList=new ArrayList<Record>();
		Record fatherRecord=SysPower.dao.getCommDbUtil().findFirst("url=?",url);
		if(fatherRecord!=null){
			for(Record record:pList){
				if(record.getStr("father_id").equals(fatherRecord.getStr("id"))){
					sonPowerList.add(record);
				}
			}
		}
		return sonPowerList;
	}
}
